package org.rslai.autotest.core.page.impl;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.rslai.autotest.core.page.AbstractHelper;
import org.rslai.autotest.core.page.ScreenShot;

/**
 * 屏幕截图工具
 * @author rslai
 */
public class ScreenShotImpl extends AbstractHelper implements ScreenShot{

	@Override
	public boolean screenShot(String pathName, String prefixFileName) throws IOException {
		return this.screenShot(pathName, false, prefixFileName);
	}

	@Override
	public boolean screenShot(String pathName, boolean isTimeStamp, String partFileName) throws IOException {
		this.createDir(pathName);

		String fileName = "";
		if (isTimeStamp) {
			fileName = org.rslai.util.time.Time.getInstance().timeStamp() + "-";
		}
		fileName = fileName + partFileName + ".png";

		this.screenShotOperation(pathName + File.separator + fileName);
		return true;
	}

	@Override
	public boolean screenShot(boolean isTimeStamp, String partFileName) throws IOException {
		String path = "report" + File.separator + "screenshot";
		this.createDir(path);

		String fileName = "";
		if (isTimeStamp) {
			fileName = org.rslai.util.time.Time.getInstance().timeStamp() + "-";
		}
		fileName = fileName + partFileName + ".png";
		
		this.screenShotOperation(path + File.separator + fileName);
		return true;
	}

	@Override
	public boolean screenShot(String partFileName) throws IOException {
		return this.screenShot(true, partFileName);
	}

	/**
	 * 截图并存放到指定位置
	 * @param fullFileName 完整路径+文件名
	 * @return true: 成功
	 * @throws IOException 
	 */
	private boolean screenShotOperation(String fullFileName) throws IOException {
		File source_file = ((TakesScreenshot) this.driver()).getScreenshotAs(OutputType.FILE); // 执行屏幕截图，默认会把截图保存到temp目录
		FileUtils.copyFile(source_file, new File(fullFileName)); // 将截图另存到我们需要保存的目录 

		return true;
	}

	/**
	 * 创建保存截图文件目录
	 * @param pathName
	 */
	private void createDir(String pathName) {
		if (!(new File(pathName).isDirectory())) {
			new File(pathName).mkdirs();
		}
	}

}
